/*
 * =====================================================================================
 *
 *       Filename:  character.cpp
 *
 *    Description:  Class for character consisting of segments
 *
 *        Version:  1.0
 *        Created:  29/06/12 20:02:41
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Moos Hueting (mh), mooshueting@gmail.com
 *   Organization:  
 *
 * =====================================================================================
 */
#include <stdlib.h>
#include "character.h"

#include <cv.h>
#include <highgui.h>
#include <iostream> // debug

using namespace cv;

Character::Character(int _sx, int _sy) {
    sx = _sx; // pixel width
    sy = _sy; // pixel height
    renderedChar = Mat(sx, sy, CV_8UC1, Scalar(0));
}

Character::Character(int _sx, int _sy, vector<Segment> _segments) {
    sx = _sx; // pixel width
    sy = _sy; // pixel height
    renderedChar = Mat(sx, sy, CV_8UC1, Scalar(0));

    segments = _segments; // segments of character
}

void Character::applyRule(Rule rule, Segment s) {
    Segment newSeg = rule.getOutput();

    newSeg.setX(s.getX());
    newSeg.setY(s.getY());

    addSegment(newSeg);
}

void Character::applyInitialRule(Rule rule) {
    Segment newSeg = rule.getOutput();
    addSegment(newSeg);
}

Segment Character::getRandomSegment() {
    return segments.at(((int)segments.size()*((float)rand() / RAND_MAX)));
}

void Character::render() {
    for (unsigned int i=0; i < segments.size(); i++) {
        // get coordinates to draw
        int x = segments.at(i).getX();
        int y = segments.at(i).getY();

        // get relative origin of segment
        int ox = segments.at(i).getOX();
        int oy = segments.at(i).getOY();

        // get dimensions of segment
        int w = segments.at(i).getWidth();
        int h = segments.at(i).getHeight();

        Mat tmp = renderedChar(Rect(x - ox, y - oy, w, h));
        segments.at(i).getSegment().copyTo(tmp);
        std::cout << segments.at(i).getSegment() << std::endl;
    }
}

void Character::display() {
    // display character in window
    Mat disp;
    resize(renderedChar, disp, Size(0,0), 10, 10, INTER_NEAREST);
    namedWindow("Character", CV_WINDOW_AUTOSIZE);
    imshow("Character", disp);
    waitKey(0);
    destroyWindow("Character");
}
